<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入优惠券标题" />
      <el-select v-model="listQuery.range" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券类型" >
        <el-option v-for="(item,index) in couponTypes" :key="index" :label="item.name" :value="item.value" />
        <el-option :label="'全部'" :value="''" />
      </el-select>
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券状态" >
        <el-option v-for="(item,index) in couponStatusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button v-permission="['coupon:list']" class="filter-item" type="primary" icon="el-icon-search" @click="search">查找</el-button>
      <el-button v-permission="['coupon:add']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中..." border fit highlight-current-row stripe>
      <el-table-column align="center" label="优惠券ID" prop="id" sortable fixed type="expand" width="100px">
        <template slot-scope="scope">
          <p>活动开始时间: {{ scope.row.activityStart }}</p>
          <p>活动结束时间: {{ scope.row.activityEnd }}</p>
          <p>备注: {{ scope.row.remark }}</p>
          <el-table :data="scope.row.couponGoodsNames" size="small" border style="width: 100%">
            <el-table-column :label="'使用范围 ('+scope.row.rangeName+')'">
              <el-table-column prop="id" label="ID" width="120"/>
              <el-table-column prop="name" label="名称"/>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" label="优惠券名称" prop="name" fixed/>
      <el-table-column align="center" label="优惠券类型" prop="rangeName"/>
      <el-table-column align="center" label="优惠券数量" prop="total">
        <template slot-scope="scope">{{ scope.row.total >= 0 ? scope.row.total : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="剩余数量" prop="remaining">
        <template slot-scope="scope">{{ scope.row.remaining >= 0 ? scope.row.remaining : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="每人限领" prop="limitNum">
        <template slot-scope="scope">{{ scope.row.limitNum >= 0 ? scope.row.limitNum : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="优惠金额" prop="discount">
        <template slot-scope="scope">减免{{ scope.row.discount }}元</template>
      </el-table-column>
      <el-table-column align="center" label="最低消费" prop="minimums">
        <template slot-scope="scope">满{{ scope.row.minimums }}元可用</template>
      </el-table-column>
      <el-table-column align="center" label="领券有效天数" prop="days">
        <template slot-scope="scope">{{ scope.row.days != 0 ? scope.row.days+'天' : "不限" }}</template>
      </el-table-column>
      <el-table-column align="center" label="活动状态" prop="statusName"/>
      <el-table-column align="center" label="操作" width="300" fixed="right">
        <template slot-scope="scope">
          <el-button v-permission="['coupon:editStatus']" v-if="scope.row.status===couponStatusMap[1].value || scope.row.status===couponStatusMap[2].value" type="primary" size="mini" @click="handleStatus(scope.row)">{{ scope.row.status===couponStatusMap[1].value?'暂停活动':'恢复活动' }}</el-button>
          <el-button v-permission="['coupon:detail']" type="info" size="mini" @click="handleEdit(scope.row)">详情</el-button>
          <el-button v-permission="['coupon:getrecord']" type="primary" icon="el-icon-tickets" size="mini" @click="queryGetRecord(scope.row)">查看领取记录</el-button>
          <el-button v-permission="['coupon:delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-permission="['coupon:list']" v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="initList"/>

    <el-dialog :close-on-click-modal="false" :title="isAdd?'新增':'编辑'" :visible.sync="dialogFormVisible" @open="loadData">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="center" label-width="100px">
        <el-form-item label="优惠券名称" prop="name" style="float:left;width:340px;">
          <el-input v-model="dataForm.name" :disabled="!isAdd"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="优惠券数量" prop="total" style="float:left;">
          <el-input v-model="dataForm.total" :disabled="!isAdd">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limitNum" style="float:left;">
          <el-input v-model="dataForm.limitNum" :disabled="!isAdd">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="优惠金额" prop="discount" style="float:left;">
          <el-input v-model="dataForm.discount" :disabled="!isAdd">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="minimums" style="float:left;">
          <el-input v-model="dataForm.minimums" :disabled="!isAdd">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="领卷有效天数" prop="days" style="float:left;">
          <el-input v-model="dataForm.days" :disabled="!isAdd">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="活动期限" style="float:left;">
          <el-date-picker :disabled="!isAdd" v-model="selectDate" value-format="yyyy-MM-dd" format="yyyy年MM月dd日" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="dateChange"/>
        </el-form-item>
        <div class="clearfix"/>
        <el-form-item label="使用范围">
          <el-radio-group v-model="dataForm.useRange" :disabled="!isAdd" @change="chooseUseRange">
            <el-radio-button v-for="(item,index) in useRanges" :key="index" :label="item.value">{{ item.name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!isAdd" v-show="dataForm.useRange === 1" label="优惠类目">
          <el-input v-model="selectCategoryNames" :disabled="!isAdd"/>
        </el-form-item>
        <el-form-item v-if="isAdd" v-show="dataForm.useRange === 1" label="优惠类目">
          <el-cascader v-model="selectCategories" :options="categories" :props="props" placeholder="优惠类目" collapse-tags clearable @change="chooseCategory"/>
        </el-form-item>
        <el-form-item v-if="!isAdd" v-show="dataForm.useRange === 2" label="优惠商品">
          <el-input v-model="selectCategoryNames" :disabled="!isAdd" type="textarea"/>
        </el-form-item>
        <el-form-item v-if="isAdd" v-show="dataForm.useRange === 2" label="优惠商品">
          <el-select v-model="dataForm.rangeId" multiple collapse-tags placeholder="请选择商品" style="width:100%">
            <el-option v-for="item in goods" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="remark" >
          <el-input v-model="dataForm.remark" :disabled="!isAdd" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-permission="['coupon:add']" v-if="isAdd" type="primary" @click="createData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :title="'用户领卷记录'" :visible.sync="dialogGetRecordVisible" width="65%">
      <coupon-get-record :coupon-id="selectCouponId"/>
    </el-dialog>
  </div>
</template>

<script>
import { CouponService } from '@/api/PromotionService'
import Pagination from '@/components/Pagination'
import Notify from '@/utils/notify'
import { ProductService, CategoryService } from '@/api/ProductService'
import CouponGetRecord from '@/views/promotion/coupon_get_record'

export default {
  name: 'Coupon',
  components: { Pagination, CouponGetRecord },
  data() {
    return {
      dataForm: { id: undefined, name: undefined, useRange: 0, rangeId: [0], remark: undefined, total: 0, remaining: 0, discount: 0, limitNum: 0, minimums: 0, days: 0, activityStart: null, activityEnd: null },
      selectDate: ['', ''], selectCategories: [], selectCategoryNames: undefined,
      couponTypes: [{ name: '全场通用卷', value: 0 }, { name: '指定类目卷', value: 1 }, { name: '指定产品卷', value: 2 }],
      props: { label: 'name', value: 'id', multiple: true },
      useRanges: [{ value: 0, name: '全场通用' }, { value: 1, name: '指定类目' }, { value: 2, name: '指定商品' }],
      couponStatusMap: [{ value: 1, name: '未开始' }, { value: 2, name: '进行中' }, { value: 3, name: '已下架' }, { value: 4, name: '已过期' }, { value: '', name: '全部' }],
      list: undefined, total: 0, listLoading: true,
      listQuery: { pageNo: 1, pageSize: 20, range: undefined, status: undefined, name: undefined },
      goods: [], categories: [], dialogFormVisible: false, isAdd: true, dialogGetRecordVisible: false, selectCouponId: undefined,
      rules: {
        name: [{ required: true, message: '优惠券标题不能为空', trigger: 'blur' }],
        total: [{ required: true, message: '优惠券总量不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }],
        limitNum: [{ required: true, message: '优惠券限领不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }],
        discount: [{ required: true, message: '优惠券折扣金额不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }],
        minimums: [{ required: true, message: '优惠券最低消费不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 9, message: '大于1,小于1亿' }],
        days: [{ required: true, message: '优惠券有效天数不能为空', trigger: 'blur' }, { pattern: /^[0-9]*$/, message: '请输入整数' }, { min: 1, max: 5, message: '最大五位的整数' }],
        activityStart: [{ required: true, message: '优惠券活动开始时间不能为空', trigger: 'blur' }],
        activityEnd: [{ required: true, message: '优惠券活动结束时间不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    initList() {
      this.listLoading = true
      CouponService.listCoupon(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    search() {
      this.listQuery.pageNo = 1
      this.initList()
    },
    resetForm() {
      this.selectDate = ['', '']
      this.dataForm = { id: undefined, name: undefined, useRange: 0, rangeId: [0], remark: undefined, total: 0, discount: 0, limitNum: 0, minimums: 0, days: 0, activityStart: null, activityEnd: null }
    },
    handleCreate() {
      this.resetForm()
      this.isAdd = true
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (parseFloat(this.dataForm.discount) > parseFloat(this.dataForm.minimums)) {
        Notify.warn(this, '最低消费不能小于折扣金额!')
        return false
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.remaining = this.dataForm.total
          CouponService.addCoupon(this.dataForm).then(() => {
            this.initList()
            this.dialogFormVisible = false
            Notify.success(this, '新增成功!')
          })
        }
      })
    },
    dateChange() {
      if (this.selectDate) {
        this.dataForm.activityStart = this.selectDate[0]
        this.dataForm.activityEnd = this.selectDate[1]
      } else {
        this.dataForm.activityStart = undefined
        this.dataForm.activityEnd = undefined
      }
    },
    handleEdit(row) {
      this.dataForm = Object.assign({}, row)
      this.isAdd = false
      this.dialogFormVisible = true
      this.selectDate = [row.activityStart, row.activityEnd]
      const array = []
      for (const index in row.couponGoodsNames) {
        array.push(row.couponGoodsNames[index].name)
      }
      this.selectCategoryNames = array.join(',')
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('您确认要删除该优惠卷吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        CouponService.deleteCoupon(row.id).then(() => {
          this.initList()
        })
      }).catch(() => {
        return false
      })
    },
    handleStatus(row) {
      const status = row.status
      let targetStatus = status
      let canEdit = false
      if (status === this.couponStatusMap[1].value) {
        // 暂停优惠卷活动
        targetStatus = this.couponStatusMap[2].value
        canEdit = true
      } else if (status === this.couponStatusMap[2].value) {
        // 恢复优惠卷活动
        targetStatus = this.couponStatusMap[1].value
        canEdit = true
      }
      if (canEdit) {
        CouponService.activeCoupon(row.id, targetStatus).then(() => {
          Notify.success(this, '修改成功!')
          this.initList()
        })
      }
    },
    chooseUseRange(range) {
      if (range === 0) {
        this.dataForm.rangeId = [0]
      } else {
        this.dataForm.rangeId = []
      }
    },
    chooseCategory() {
      const selected = []
      for (const index in this.selectCategories) {
        const array = this.selectCategories[index]
        selected.push(array[array.length - 1])
      }
      this.dataForm.rangeId = selected
    },
    loadData() {
      this.loadCategory()
      this.loadProducts()
    },
    loadCategory() {
      CategoryService.loadCategoryTree().then(result => {
        this.categories = result
      })
    },
    loadProducts() {
      ProductService.loadAllProductNames().then(result => {
        this.goods = result
      })
    },
    queryGetRecord(row) {
      this.dialogGetRecordVisible = true
      this.selectCouponId = row.id
    }
  }
}
</script>
